package ml.kupin.sso.controller;

import ml.kupin.common.utils.KuPinResult;
import ml.kupin.pojo.TbUser;
import ml.kupin.sso.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户注册Controller
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.6 10:21.
 */
@Controller
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    @RequestMapping("/reg")
    public String showRegisterPage() {
        return "register";
    }

    /**
     * 使用Ajax检查用户名、电话、邮箱是否被占用，返回KupinResult，其中data为boolean类型的值
     * 链接形式：/user/check/检查的值/1  【1 用户名，2 电话，3 邮箱】
     */
    //MediaType.APPLICATION_JSON_UTF8_VALUE = "application/json" + ";charset=UTF-8";
    @RequestMapping(value = "/check/{param}/{type}", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public KuPinResult checkRegisterData(@PathVariable String param, @PathVariable Integer type) {
        KuPinResult kuPinResult = registerService.checkData(param, type);
        return kuPinResult;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public KuPinResult register(TbUser user) {
        KuPinResult kuPinResult = null;
        try {
            //调用服务层执行注册操作
            kuPinResult = registerService.createUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            //服务层抛出异常，注册失败
            return KuPinResult.notOk("非常抱歉，您此次注册操作未成功，请稍后重试！");
        }
        //服务层未抛出异常，并返回了KupinResult对象
        return kuPinResult;
    }


}
